import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Card, Drawer, Form, Input, Modal, Radio, Select, Space, Table, Tag } from "antd"
import { useState } from "react";
import { DELETE_PLAYER, GET_PLAYER, PATCH_PLAYER } from "../../api/player";
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { useResHook } from "../../utils/useResponseHook";


// 封装action操作组件
function Actions({ player, refresh, open, showDrawer }) {
  // 设置模态框确定删除 
  // const [modal, contextHolder] = Modal.useModal();
  let confirm = () => {
    // 模态框弹窗
    Modal.confirm({
      title: '警告',
      // 图标为图标库中的组件，需要引入
      icon: <ExclamationCircleOutlined />,
      content: '删除后数据无法回复，请确认删除！！！',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        remove()
      }
    });
  }
  let remove = (id) => {
    // console.log(id);
    DELETE_PLAYER(id).then((res) => {
      // console.log(res);
      // console.log("删除成功");
      // 调用页面刷新
      refresh();
    })
  }
  // 编辑edit
  let edit = () => {
    showDrawer(player)
  }
  return (
    <>
      {/* {contextHolder} */}
      <Space>
        <Button type="primary" onClick={() => edit()}>编辑</Button>
        <Button type="primary" danger onClick={() => { confirm(player.id) }}>删除</Button>
      </Space>

    </>

  );
}




function Filter({ changeFilterParams }) {
  let submit = (values) => {
    // 年龄判断
    let { minAge, maxAge } = values
    values.age = (minAge ? minAge : "0") + "-" + (maxAge ? maxAge : "9999")
    values.page = 1
    console.log(values);
    changeFilterParams(values);
  }

  // 获取form表单dom元素
  let [form] = Form.useForm()
  let reset = () => {
    form.resetFields();
    changeFilterParams({ page: 1, name: null, gender: null, age: "0-9999" });
  }
  return (
    <Space>
      <Form form={form} name="filterForm" onFinish={submit}>
        <Space>
          <Form.Item name="name" label="姓名">
            <Input placeholder="请输入用户名查询！"></Input>
          </Form.Item>
          <Form.Item name="gender" label="性别">
            <Select placeholder="请选择性别" options={[
              { value: 0, label: "男" },
              { value: 1, label: "女" }
            ]}>
              {/* <Select.Option value="0">男</Select.Option>
              <Select.Option value="1">女</Select.Option> */}
            </Select>
          </Form.Item>
          <Form.Item label="年龄区间" style={{ display: "flex" }}>
            {/* <Input name="minAge" style={{ width: 100, textAlign: 'center' }} placeholder="最小年龄" />
            <Input className="site-input-split" style={{ width: 30 }} placeholder="~" disabled />
            <Input name="maxAge" className="site-input-right" style={{ width: 100, textAlign: 'center' }} placeholder="最大年龄" /> */}
            <Input.Group style={{ alignItems: "center" }} compact >
              <Form.Item name="minAge" style={{ alignItems: "center" }}>
                <Input style={{ width: 100, textAlign: 'center' }} placeholder="最小年龄" />
              </Form.Item>
              <Form.Item>
                <Input style={{ width: 30 }} placeholder="~" disabled />
              </Form.Item>
              <Form.Item name="maxAge">
                <Input style={{ width: 100, textAlign: 'center' }} placeholder="最大年龄" />
              </Form.Item>
            </Input.Group>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">查询</Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={() => reset()}>重置</Button>
          </Form.Item>
        </Space>
      </Form>
    </Space>
  );
}





function PlayerList() {
  // 设置列数据
  let columns = [
    {
      title: '姓名',
      dataIndex: "name",
      key: "name"
    },
    {
      title: '性别',
      dataIndex: "gender",
      key: "gender",
      // render函数进行页面的渲染。实现复杂数据的渲染，参数分别为当前行的值，当前行数据，行索引
      render: (text, record) => text ? <Tag color={"green"}>女</Tag> : <Tag color={"geekblue"}>男</Tag>  // <span>{text}- {JSON.stringify(record)}</span>
    },
    {
      title: '年龄',
      dataIndex: "age",
      key: "age"
    },
    {
      title: '操作',
      dataIndex: "action",
      key: "action",
      render: (text, player) => {
        return (
          <Actions refresh={refresh} open={open} showDrawer={showDrawer} player={player} ></Actions>
        )
      }
    }
  ]
  let [params, setParams] = useState({
    name: null,
    gender: null,
    age: null,
    page: 1,
    limit: 10
  })


  let changeFilterParams = (data) => {
    // 通过展开的方式便于以后增加params需要传递的值
    // console.log(data);
    setParams({
      ...params,
      ...data
    })

    console.log(params);
  }
  // // 封装为一个hook，实现获取数据，页面刷新；传递请求的方法时不要传递函数调用，直接传递函数名，否则会执行多次调用请求
  let { data, loading, total, refresh } = useResHook(GET_PLAYER, params);


  // 抽屉
  let [open, setOpen] = useState(false)
  let [player, setPlayer] = useState({})
  let showDrawer = (player) => {
    setOpen(true)
    setPlayer(player)
  }
  let submit = async (values) => {
    let { id, ...data } = values
    let res = await PATCH_PLAYER(id, data)
    // console.log(res);
    // console.log(values);
    setOpen(false)
    refresh()
  }


  // // 获取Search组件
  // let { Search } = Input
  // // 创建存储用户源数据
  // let [searchValue, setSearchValue] = useState("")
  // // 筛选的搜索 let _data = data.filter(d => d.name.indexOf(value) > 0)
  // let search = (value) => {
  //   // playerData = data.filter(d => d.name.indexOf(value) > 0)
  //   console.log(data.filter(d => d.name.indexOf(value) > 0));
  //   setSearchValue(value)
  // }
  return (
    <Space style={{ display: "flex" }} direction="vertical">
      <Card>
        <Filter changeFilterParams={changeFilterParams}></Filter>
      </Card>
      <Table rowKey="id" loading={loading} columns={columns} dataSource={data} pagination={{
        total,
        onChange: (page, limit) => {
          console.log(page, limit);
          setParams({
            ...params,
            page,
            limit
          })
        }
      }}></Table>
      {/* open开关，onClose关闭事件 */}
      <Drawer open={open} onClose={() => setOpen(false)}>
        {/* 抽屉，实现编辑效果，抽屉中为from表单 */}
        {
          open ? <Form onFinish={submit} initialValues={player} layout="vertical">
            <Form.Item label="id" name="id">
              <Input readOnly></Input>
            </Form.Item >
            <Form.Item label="姓名" name="name">
              <Input></Input>
            </Form.Item>
            <Form.Item label="性别" name="gender">
              <Radio.Group >
                <Radio value={0}>男</Radio>
                <Radio value={1}>女</Radio>
              </Radio.Group>
              {/* <Input></Input> */}
            </Form.Item>
            <Form.Item label="年龄" name="age">
              <Input></Input>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">修改</Button>
            </Form.Item>
          </Form> : null
        }
      </Drawer>
    </Space>
  );
}




export default PlayerList;